<template>
  <n-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-placement="left"
    label-width="auto"
    require-mark-placement="right-hanging"
    :disabled="isSubmitting"
    class="py-4"
  >
    <n-grid :cols="2" :x-gap="24">
      <n-form-item-grid-item label="学校名称" path="schoolName">
        <n-input v-model:value="formData.schoolName" placeholder="请输入学校全称" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="学校标准码" path="schoolCode">
        <n-input v-model:value="formData.schoolCode" placeholder="请输入学校标准码" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="主管部门" path="governingDepartment">
        <n-select
          v-model:value="formData.governingDepartment"
          placeholder="请选择或输入主管部门"
          :options="governingDepartmentOptions"
          filterable
          tag
        />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="所在地" path="location">
        <n-select
          v-model:value="formData.location"
          placeholder="请选择或输入所在地"
          :options="locationOptions"
          filterable
          tag
        />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="中央直属" path="isCentral">
        <n-select
          v-model:value="formData.isCentral"
          placeholder="请选择是否为中央直属"
          :options="booleanStatusOptions"
        />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="联系人姓名" path="contactName">
        <n-input v-model:value="formData.contactName" placeholder="请输入高校联系人姓名" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="联系人部门" path="contactDepartment">
        <n-input v-model:value="formData.contactDepartment" placeholder="请输入高校联系人部门" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="联系人职务" path="contactPosition">
        <n-input v-model:value="formData.contactPosition" placeholder="请输入高校联系人职务" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="座机电话" path="landlinePhone">
        <n-input v-model:value="formData.landlinePhone" placeholder="请输入座机电话" />
      </n-form-item-grid-item>
      <n-form-item-grid-item label="手机号码" path="mobilePhone">
        <n-input v-model:value="formData.mobilePhone" placeholder="请输入手机号码" />
      </n-form-item-grid-item>
      <n-form-item-grid-item :span="2" label="备注" path="remarks">
        <n-input
          v-model:value="formData.remarks"
          type="textarea"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </n-form-item-grid-item>
    </n-grid>

    <div class="flex justify-between mt-6">
      <div>
        <n-button v-if="!initialData" @click="generateMockData" type="info" ghost>
          🎲 一键生成虚拟信息
        </n-button>
      </div>
      <div>
        <n-button @click="handleCancel" :disabled="isSubmitting" class="mr-4">取消</n-button>
        <n-button type="primary" @click="handleSubmit" :loading="isSubmitting" :disabled="isSubmitting">
          {{ initialData ? '保存更新' : '创建' }}
        </n-button>
      </div>
    </div>
  </n-form>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, onMounted } from 'vue';
import {
  NForm,
  NFormItemGridItem,
  NInput,
  NSelect,
  NButton,
  NGrid,
  useMessage
} from 'naive-ui';
import { booleanStatusOptions, governingDepartmentOptions, locationOptions } from '@/utils/constants';

const props = defineProps({
  initialData: {
    type: Object,
    default: null,
  },
});

const emits = defineEmits(['submit', 'cancel']);

const message = useMessage();
const formRef = ref(null);
const defaultFormValues = {
  id: null,
  schoolName: '',
  schoolCode: '',
  governingDepartment: null,
  location: null,
  isCentral: null,
  contactDepartment: '',
  contactPosition: '',
  contactName: '',
  landlinePhone: '',
  mobilePhone: '',
  remarks: '',
};
const formData = ref({ ...defaultFormValues });
const isSubmitting = ref(false);

const rules = {
  schoolName: { required: true, message: '请输入学校名称', trigger: ['input', 'blur'] },
  schoolCode: { required: true, message: '请输入学校标准码', trigger: ['input', 'blur'] },
  isCentral: { type: 'boolean', required: true, message: '请选择是否为中央直属', trigger: ['change', 'blur'] },
  contactName: { required: true, message: '请输入联系人姓名', trigger: ['input', 'blur'] },
  landlinePhone: { required: true, message: '请输入座机电话', trigger: ['input', 'blur'] },
  mobilePhone: { required: true, message: '请输入手机号码', trigger: ['input', 'blur'] },
};

watch(() => props.initialData, (newData) => {
  if (newData) {
    formData.value = { ...defaultFormValues, ...newData };
  } else {
    formData.value = { ...defaultFormValues };
  }
}, { immediate: true, deep: true });

const handleSubmit = async (e) => {
  if (isSubmitting.value) return; // 防止重复提交

  e.preventDefault();
  try {
    isSubmitting.value = true;
    await new Promise((resolve, reject) => {
      formRef.value?.validate((errors) => {
        if (!errors) {
          resolve();
        } else {
          reject(new Error('表单验证失败'));
        }
      });
    });

    await emits('submit', { ...formData.value });
  } catch (error) {
    console.error('表单提交失败:', error);
    message.error('请检查表单填写是否正确');
  } finally {
    isSubmitting.value = false;
  }
};

const handleCancel = () => {
  emits('cancel');
};

const resetForm = () => {
  formData.value = { ...defaultFormValues };
  formRef.value?.restoreValidation();
};

// 生成虚拟数据的函数
const generateMockData = () => {
  const schoolNames = [
    '清华大学', '北京大学', '复旦大学', '上海交通大学', '浙江大学',
    '中国科学技术大学', '南京大学', '华中科技大学', '中山大学', '哈尔滨工业大学',
    '西安交通大学', '北京航空航天大学', '同济大学', '东南大学', '北京理工大学'
  ];

  const contactNames = ['张教授', '李主任', '王老师', '赵处长', '钱院长', '孙博士', '周主管', '吴老师'];
  const contactDepartments = ['教务处', '学生处', '科研处', '人事处', '财务处', '国际交流处', '招生办', '就业指导中心'];
  const contactPositions = ['处长', '副处长', '主任', '副主任', '科长', '副科长', '专员', '助理'];

  const governingDepts = governingDepartmentOptions.map(opt => opt.value);
  const locations = locationOptions.map(opt => opt.value);

  const randomIndex = Math.floor(Math.random() * schoolNames.length);
  const randomContactIndex = Math.floor(Math.random() * contactNames.length);
  const randomDeptIndex = Math.floor(Math.random() * contactDepartments.length);
  const randomPosIndex = Math.floor(Math.random() * contactPositions.length);

  // 生成随机学校标准码
  const generateSchoolCode = () => {
    return '10' + String(Math.floor(Math.random() * 900) + 100);
  };

  // 生成随机联系方式
  const generateLandlinePhone = () => {
    const areaCodes = ['010', '021', '020', '025'];
    const areaCode = areaCodes[Math.floor(Math.random() * areaCodes.length)];
    const number = Math.floor(Math.random() * 90000000) + 10000000;
    return `${areaCode}-${number}`;
  };

  const generateMobilePhone = () => {
    const prefixes = ['138', '139', '150', '151', '152', '158', '159', '188', '189'];
    const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
    const suffix = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
    return prefix + suffix;
  };

  // 填充表单数据
  formData.value = {
    ...defaultFormValues,
    schoolName: schoolNames[randomIndex],
    schoolCode: generateSchoolCode(),
    governingDepartment: governingDepts[Math.floor(Math.random() * governingDepts.length)],
    location: locations[Math.floor(Math.random() * locations.length)],
    isCentral: Math.random() > 0.5,
    contactDepartment: contactDepartments[randomDeptIndex],
    contactPosition: contactPositions[randomPosIndex],
    contactName: contactNames[randomContactIndex],
    landlinePhone: generateLandlinePhone(),
    mobilePhone: generateMobilePhone(),
    remarks: `这是${schoolNames[randomIndex]}的虚拟测试数据`,
  };


};

defineExpose({
  resetForm,
});

onMounted(() => {
  if (props.initialData) {
    formData.value = { ...defaultFormValues, ...props.initialData };
  }
});
</script>